package com.cuijq.dubbo.core.server;


import com.cuijq.dubbo.demo.Invocation;
import org.springframework.cloud.client.ServiceInstance;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {
    public static <T> T getProxy(NettyClient nettyClient, Class interfaceClass, ServiceInstance instance) {
        Object proxyInstance = Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(), new Class[]{interfaceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try {
                            Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(),
                                    method.getParameterTypes(),
                                    args);
                            return nettyClient.send(instance.getHost(), instance.getPort(), invocation);
                        } catch (Exception e) {
                            return "容错";
                        }
                    }
                });
        return (T) proxyInstance;
    }
}

